package com.rattsoftware.client.controllers;

import com.extjs.gxt.ui.client.event.EventType;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.rattsoftware.client.AppMessages;
import com.rattsoftware.client.RattsAsyncCallback;
import com.rattsoftware.client.RefreshableEvent;
import com.rattsoftware.client.RefreshablePublisher;
import com.rattsoftware.client.service.RoleServiceAsync;
import com.rattsoftware.client.service.UserServiceAsync;
import com.rattsoftware.client.views.NewEditUserView;
import com.rattsoftware.server.admin.model.User;

public class NewEditUserController extends Controller {
    AppMessages appMessages = GWT.create(AppMessages.class);
    private UserServiceAsync userService;
    private RoleServiceAsync roleService;
    private NewEditUserView newUserView;

    public final static EventType NEWUSER = new EventType();
    public final static EventType EDITUSER = new EventType();
    
    private RoleUserAccessController roleUserAccessController;

    public NewEditUserController(UserServiceAsync aUserService, RoleServiceAsync aRoleService) {
        super();
        userService = aUserService;
        roleService = aRoleService;
        registerEventTypes(NEWUSER);
        registerEventTypes(EDITUSER);
        roleUserAccessController = new RoleUserAccessController(roleService);
    }
    
    @Override
    protected void initialize() {
    	GWT.log("NewUserController : initialize");
    }

    public void handleEvent(AppEvent event) {
    	GWT.log("NewUserController : handleEvent");
        EventType type = event.getType();
        if (type == NEWUSER) {
        	newUserView = new NewEditUserView(type, this);
            forwardToView(newUserView, event);
        }
        if (type == EDITUSER) {
        	newUserView = new NewEditUserView(type, this);
            forwardToView(newUserView, event);
        }
    }

    public void isUserNameUnique(final String userName) {
        GWT.log("NewUserController : getCheckUserNameUnique");
        userService.getUser(userName, new AsyncCallback<User>() {
            public void onSuccess(User result) {
            	newUserView.setUserNameUnique(userName, false);
            }
            @Override
            public void onFailure(Throwable throwable) {
            	if (throwable instanceof Exception) {
            		newUserView.setUserNameUnique(userName, true);
            	}
            }
        });
    }

	public void isEmailUnique(final String userName, final String email) {
		GWT.log("NewUserController : getCheckEmailUnique ");
		userService.findUserByEmail(email, new AsyncCallback<User>() {
			@Override
			public void onSuccess(User result) {
				if (result.getUsername().equals(userName)) {
					// in the case when the user is being edited, we check that the user returned on the email search is not themselves
					newUserView.setEmailUnique(email, true);
				} else {
					newUserView.setEmailUnique(email, false);
				}
			}
			@Override
			public void onFailure(Throwable throwable) {
				if (throwable instanceof Exception) {
					newUserView.setEmailUnique(email, true);
				}
			}
		});
	}

    public void saveUser(final User user, final boolean triggerRefreshEvent, final boolean notifyMe) {
        GWT.log("NewUserController : saveUser");
        userService.saveUser(user, new RattsAsyncCallback<User>() {
            @Override
            public void onSuccess(User result) {
                if (triggerRefreshEvent) {
                	if (user.getId().equals("0")) {
                		RefreshablePublisher.get().publish(new RefreshableEvent(RefreshableEvent.Type.CREATE_USER, result));
                	} else {
                		RefreshablePublisher.get().publish(new RefreshableEvent(RefreshableEvent.Type.UPDATE_USER, result));
                	}
                }
                setUserForAccessMapping(result);
                if (notifyMe) {
                	newUserView.saved(result);
                }
            }
        });
    }
    
    public void getUser(String username) {
    	userService.getUser(username, new RattsAsyncCallback<User>() {
            @Override
            public void onSuccess(User result) {
                setUserForAccessMapping(result);
                newUserView.loaded(result);
            }
        });
    }
    
    public RoleUserAccessController getRoleUserAccessController() {
    	return roleUserAccessController;
    }
    
    public void setUserForAccessMapping(User user) {
    	roleUserAccessController.setUser(user);
    }
}